package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.AppJwtUtil;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.UserHolder;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.db.User;
import com.tanhua.model.domain.db.UserInfo;
import com.tanhua.server.config.MqMessageService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private MqMessageService mqMessageService;


    /**
     * 发送短信验证码
     * @param phone
     */
    public void sendMsg(String phone) {
        //1、随机生成6位数字
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2、调用template对象，发送手机短信
        //template.sendSms(phone,code);
        //3、将验证码存入到redis
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));
    }


    /**
     * 验证登录
     * @param phone
     * @param code
     */
    public Map loginVerification(String phone, String code) {
        //设置类型
        String type = "01";

        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if(StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            throw new RuntimeException("验证码错误");
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        //4、通过手机号码查询用户
        User user = userApi.findByMobile(phone);
        boolean isNew = false;
        //5、如果用户不存在，创建用户保存到数据库中
        if(user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;

            //注册环信用户
            String hxUser = "hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if(create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }

        }
        //判断用户是否被冻结
        userFreezeService.checkUserStatus(user.getId());

        //日志消息
        mqMessageService.sendLogServiceMessage(user.getId(),type,"user",null);

        //6、通过JWT生成token(存入id和手机号码)
        String token = AppJwtUtil.getToken(user.getId());
        //7、构造返回值
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);

        return retMap;
    }

    /**
     * 3、完善个人信息（新用户）
     * @param userInfo
     */
    public void loginReginfo(UserInfo userInfo) {

        Long id = UserHolder.getUserId();
        //补充用户id
        userInfo.setId(id);
        //年龄的默认值
        userInfo.setAge(18);
        //3、将id数据及userInfoVo补充到userInfo中，再实现数据保存
        userInfoService.save(userInfo);

    }

    @Autowired
    private OssTemplate ossTemplate;//文件上传的模板对象（自定义的自动装配）
    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 4、头像上传

     * @param headPhoto
     * @return
     */
    public void uploadHead(MultipartFile headPhoto) {
        //1、token校验
        Long id = UserHolder.getUserId();

        //3、文件上传
        try {
            String headUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            //上传的头像是否是人像？
            //非人像的不得上传（人脸识别）
            boolean flag = aipFaceTemplate.detect(headUrl);
            if (!flag){
                throw new RuntimeException("上传头像非人像！");
            }
            //根据id保存headUrl
            userInfoService.saveHead(id,headUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
